package com.apollo.java.config;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigChangeListener;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.model.ConfigChange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author: LiuWei
 * @date: Create in 16:45 2018/08/09
 */
public class TestConfig {

    private static final Logger logger = LoggerFactory.getLogger(TestConfig.class);

    private Config config;

    public TestConfig() {
        ConfigChangeListener changeListener = changeEvent -> {
            logger.info("Changes for namespace {}", changeEvent.getNamespace());
            for (String key : changeEvent.changedKeys()) {
                ConfigChange change = changeEvent.getChange(key);
                logger.info("Change - key: {}, oldValue: {}, newValue: {}, changeType: {}",
                        change.getPropertyName(), change.getOldValue(), change.getNewValue(),
                        change.getChangeType());
            }
        };
        config = ConfigService.getAppConfig();
        config.addChangeListener(changeListener);
    }

    public String getConfig(String key) {
        String result = config.getProperty(key, "null");
        logger.info(String.format("Loading key : %s with value: %s", key, result));
        return result;
    }
}
